<!--  -->
<template>
  <div>
    <div>
      <slot :params="params" :searchSubmit="searchSubmit" name="search"></slot>
    </div>
    <div>
      <slot :deleteAllHandle="deleteAllHandle" name="buttons"></slot>
    </div>
    <div>
      <el-table  v-loading="loading" @selection-change="handleSelectionChange" :data="state.list" style="width: 100%">
        <el-table-column v-if="props.isSelection" type="selection" width="40" />
        <el-table-column v-for="column in props.columns" :prop="column.prop" :label="column.label"
          v-bind="column.attrs">
          <!-- 插槽 自定义字段 -->
          <template v-if="column.slot" #default="scope">
            <slot :name="column.prop" :deleteHandle="deleteHandle" :scope="scope"></slot>
          </template>
            <!-- 时间格式化 -->
            <template v-if="column.timeFormat" #default="scope">
                 {{ formatTime(scope.row[column.prop],column.timeFormat) }}
          </template>
          <!-- 单张图片 -->
          <template v-if="column.image" #default="scope">
            <el-image style="width: auto; height:40px" :src="imgBaseUrl + scope.row[column.prop]" :zoom-rate="1.2"
              :max-scale="7" :min-scale="0.2" preview-teleported :preview-src-list="[imgBaseUrl + scope.row[column.prop]]"
              :initial-index="4" fit="cover" />
          </template>
          <!-- 多张图片 -->
          <template v-if="column.images" #default="scope">
            <el-image v-for="item in scope.row[column.prop]" style="width: auto; height:40px;margin-left:10px;" :src="imgBaseUrl + item.url"
              :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" preview-teleported
              :preview-src-list="scope.row[column.prop].map((item: any) => imgBaseUrl + item.url)" :initial-index="4"
              fit="cover" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination v-if="props.pageConfig.isShow" @size-change="handleSizeChange" @current-change="handleCurrentChange"
      class="page" v-model:current-page="params.page" v-model:page-size="params.psize"
      :page-sizes="props.pageConfig.pageSizes" background layout="total, sizes, prev, pager, next, jumper"
      :total="state.total" />
  </div>
</template>

<script lang='ts' setup>
import { reactive, toRefs, ref, onMounted, defineEmits, defineExpose } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import moment from 'moment';
const imgBaseUrl = ref(import.meta.env.VITE_IMG_URL);

const formatTime=(val:string,format:string)=>{
  return moment(val).format(format);
}

type ColumnType = {
  prop: string,
  label: string,
  slot?: boolean,
  attrs?: any,
  image?: boolean,
  images?: boolean,
  timeFormat?:string | undefined
}
type PageConfig = {
  psize?: number,
  isShow?: boolean,
  pageSizes?: number[],
}
export type TableType = {
  columns: Array<ColumnType>,
  loadData: Function,
  delete?: Function,
  deleteAll?: Function,
  pageConfig?: PageConfig,
  searhParams?: any,
  isSelection?: boolean
}
const loading=ref(false);
//接收传过来的列
const props = withDefaults(defineProps<TableType>(), {
  columns: () => [],
  loadData: () => () => { },
  delete: () => () => { },
  deleteAll: () => () => { },
  pageConfig: () => ({
    psize: 15,
    isShow: true,
    pageSizes: [15, 30, 50, 100, 300]
  }),
  searhParams: () => ({}),
  isSelection: true
})
if (props.pageConfig.psize == undefined) {
  props.pageConfig.psize = 15;
}
if (props.pageConfig.isShow == undefined) {
  props.pageConfig.isShow = true;
}
if (props.pageConfig.pageSizes == undefined) {
  props.pageConfig.pageSizes = [15, 30, 50, 100, 300];
}
console.log(props.pageConfig);
// const isSelection=ref(true)
const params = reactive<any>({
  page: 1,
  psize: props.pageConfig.psize

})
const state = reactive({
  total: 0,
  list: []
})
//搜索
const searchSubmit = () => {
  params.page = 1;
  getData();
}
const getData = async () => {
  console.log(99999, "请求数据");

  loading.value=true;

  let _params = { ...props.searhParams, ...params };
  const res: any = await props.loadData(_params).catch(()=>{});
  if (res.errCode === 10000) {
    state.list = res.data.list;
    state.total = res.data.counts;
  }
   loading.value=false;
}

//单个删除
const deleteHandle = async (id: number) => {

  const confirm = await ElMessageBox.confirm('是否要删除该条记录?').catch(() => { })
  if (!confirm) return;
  const res: any = await props.delete(id).catch(() => { });
  if (res.errCode === 10000) {
    getData();
  }

}
const emit = defineEmits(["multipleSelection"])
//多选
const multipleSelection = ref<any[]>([])
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
  emit("multipleSelection", val);

}


//批量删除
const deleteAllHandle = async () => {
  if (!multipleSelection.value.length) {
    ElMessage.error('亲，请选择要删除的记录');
    return;
  }

  const confirm = await ElMessageBox.confirm('是否要删除选中的记录?').catch(() => { })
  if (!confirm) return;

  let ids = multipleSelection.value.map(item => item.id);

  const res: any = await props.deleteAll(ids).catch(() => { });
  if (res.errCode === 10000) {
    getData();
  }


}

//分页事件
const handleSizeChange = (val: number) => {
  params.psize = val;
  getData();
}
const handleCurrentChange = (val: number) => {
  params.page = val;

  getData();
}
onMounted(() => {
  getData();
})


defineExpose({ getData, params });
// const tableData = [
//   {
//     date: '2016-05-03',
//     name: 'Tom',
//     address: 'No. 189, Grove St, Los Angeles',
//   },
//   {
//     date: '2016-05-02',
//     name: 'Tom',
//     address: 'No. 189, Grove St, Los Angeles',
//   },
//   {
//     date: '2016-05-04',
//     name: 'Tom',
//     address: 'No. 189, Grove St, Los Angeles',
//   },
//   {
//     date: '2016-05-01',
//     name: 'Tom',
//     address: 'No. 189, Grove St, Los Angeles',
//   },
// ]
</script>
<style scoped>
.page {
  margin: 30px 0px;
  display: flex;
  justify-content: center;
}
</style>